<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.flowArrange_delete" @click="handleDelete">删 除</el-button>
      </template>
      <template slot="scriptDataForm">
        <div style="border: 1px solid #dcdfe6; border-radius: 4px">
          <editor
            :value="scriptData"
            @input="handleInput"
            @init="editorInit"
            :lang="aceConfig.selectLang"
            :theme="aceConfig.selectTheme"
            :options="aceConfig.options"
            width="100%"
            height="400px"
          />
        </div>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import { getList, getDetail, remove, addOrUpdate } from '@/api/flow/flow-arrange.js';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
// 编辑器主题
const themes = ['xcode', 'eclipse', 'monokai', 'cobalt'];
// 编辑器语言
const langs = ['groovy', 'javascript', 'python', 'lua'];
// tabs
const tabs = [2, 4, 8];
// 字体大小
const fontSizes = [14, 15, 16, 17, 18, 19, 20, 21, 22];
// 编辑器选项
const options = {
  tabSize: 4, // tab默认大小
  showPrintMargin: false, // 去除编辑器里的竖线
  fontSize: 20, // 字体大小
  highlightActiveLine: true, // 高亮配置
  enableBasicAutocompletion: true, //启用基本自动完成
  enableSnippets: true, // 启用代码段
  enableLiveAutocompletion: true // 启用实时自动完成
};
export default {
  name: 'FlowRulesManager',
  components: {
    CommonModalTemplate,
    editor: require('vue2-ace-editor'),
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'FLOW_ARRANGE',
      modalName: '',
      form: {},
      query: {},
      defaults: {},
      timer: new Date().getTime(),
      editDialog: false,
      loading: false,
      data: [],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        // dialogWidth: '35%',
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 4,
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        labelWidth: 110,
        border: true,
        span: 24,
        index: true,
        indexLabel: '序号',
        addBtn: true,
        editBtn: true,
        delBtn: true,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: '应用程序',
            prop: 'applicationName',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入应用',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '脚本类型',
            prop: 'scriptType',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=scriptType',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            value: 'script',
            rules: [
              {
                required: true,
                message: '请输入脚本类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '脚本语言',
            prop: 'scriptLanguage',
            search: true,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=scriptLang',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            value: 'javascript',
            rules: [
              {
                required: true,
                message: '请输入脚本语言',
                trigger: 'blur'
              }
            ],
            change: (val) => {
              this.aceConfig.selectLang = val.value;
              this.editorInit();
            }
          },
          {
            label: '脚本名称',
            prop: 'scriptName',
            search: true,
            type: 'input',
            rules: [
              {
                required: true,
                message: '请输入脚本名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '脚本',
            prop: 'scriptData',
            type: 'textarea',
            span: 24,
            maxRows: 3,
            minRows: 3,
            rules: [
              {
                required: true,
                message: '请输入脚本',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            maxRows: 3,
            minRows: 3
          },
          {
            label: '启用',
            prop: 'status',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            value: 1
          }
        ]
      },
      tableOption: {}, //公用模态框配置信息
      aceConfig: {
        // 代码块配置
        langs, // 语言
        themes, // 主题
        tabs, // tab空格
        fontSizes,
        options, // 编辑器属性设置
        selectTheme: 'xcode', // 默认选择的主题
        selectLang: 'javascript', // 默认选择的语言
        readOnly: false // 是否只读
      },
      scriptData: ''
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.flowArrange_add, false),
        delBtn: this.vaildData(this.permission.flowArrange_delete, false),
        editBtn: this.vaildData(this.permission.flowArrange_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    /**
     * 提交保存
     */
    rowSave(row, done, loading) {
      addOrUpdate(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      addOrUpdate(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete(row) {
      if (this.selectionList.length === 0 && !row.id) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    /**
     * 打开avue-crud之前的调用
     */
    beforeOpen(done, type) {
      this.scriptData = this.form.scriptData;
      done();
    },
    beforeClose(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // 当该组件中的值改变时，通过该方法将该组件值传给父组件，实现组件间双向绑定
    handleInput(e) {
      this.form.scriptData = e;
    },
    // 显示'编辑器设置'模态窗口
    showSettingModal() {
      this.visible = true;
    },
    // '编辑器设置'模态窗口确认按钮回调
    handleOk() {
      this.visible = false;
      // this.editorInit()
    },
    //分割线：以下为该代码组件的配置
    // 代码块主题切换
    handleThemeChange() {
      this.editorInit();
    },
    // 代码块语言切换
    handleLangChange() {
      this.editorInit();
    },
    // tab切换
    handleTabChange(value) {
      this.aceConfig.options.tabSize = value;
      this.editorInit();
    },
    // 字体大小切换
    handleFontChange(value) {
      this.aceConfig.options.tabSize = value;
      this.editorInit();
    },
    // 代码块初始化
    editorInit() {
      console.log(this.aceConfig.selectLang);
      require('brace/ext/language_tools'); // language extension prerequsite...
      require(`brace/mode/${this.aceConfig.selectLang}`); // 语言
      require(`brace/theme/${this.aceConfig.selectTheme}`); // 主题
    }
  }
};
</script>

<style></style>
